package com.ks.test.app;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;

public class Demo6 {

    public static void main(String[] args) throws Exception {
        // attempted  duplicate class definition for name: "com/ks/test/app/Hello"
        // then the original Hello class is loaded at the first line of main and the call to toClass() throws an exception since the class loader cannot load two different versions of the Hello class at the same time.
        // Hello orginal = new Hello();

        ClassPool cp = ClassPool.getDefault();
        CtClass cc = cp.get("com.ks.test.app.Hello");
        CtMethod m = cc.getDeclaredMethod("say");
        m.insertBefore("{ System.out.println(\"Hello.say():\"); }");
        Class c = cc.toClass();
        Hello h = (Hello) c.newInstance();
        h.say();
    }

}

class Hello {

    public void say() {
        System.out.println("Hello");
    }
}
